package com.zm.openapi.filters;

import com.zm.openapi.enums.CommonEnum;
import com.zm.openapi.constants.FilterSeq;
import com.zm.openapi.exception.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 启动的时候从运营平台把相关的 appid + secret 等信息缓存过来
 * 并做定时失效处理
 * 可以用 guava.cache 来处理
 *
 *
 */
@Slf4j
@Component
public class UrlCheckFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        String uri = serverHttpRequest.getURI().getPath();
        if(!StringUtils.startsWith(uri, "/openapi")) {
            log.error(CommonEnum.ERROR_UNAUTHED_API_PATH.getMsg());
            return Mono.error(new ValidationException(CommonEnum.ERROR_UNAUTHED_API_PATH));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return FilterSeq.SEQ_FIRST;
    }

}
